package com.algorithm.testutils;/*
 *@Author:DOWN
 *@Date:2021/12/13 10:42
 *@Comment: 排序算法测试工具类
 */

import java.lang.reflect.Method;

public class SortingHelp {
    public SortingHelp() {
    }

    /**
     * 用于验证排序是否成功
     * @param arrs 泛型数组
     * @param <E> 泛型Type
     * @return boolean
     */
    public static <E extends Comparable<E>> boolean isSorted(E[] arrs) {
        for (int i = 0; i < arrs.length - 1; i++) {
            if (arrs[i].compareTo(arrs[i + 1]) > 0) {
                return false;
            }
        }
        return true;
    }
    public static <E extends Comparable<E>> boolean isReverseSorted(E[] arrs) {
        for (int i = 0; i < arrs.length - 1; i++) {
            if (arrs[i].compareTo(arrs[i + 1]) < 0) {
                return false;
            }
        }
        return true;
    }
    /**
     * 用于反射各种排序算法的执行方法
     * @param path Class路径
     * @param arrs 泛型数组
     * @param <E> 泛型Type
     * @throws Exception 反射或算法异常
     */
    public static <E extends Comparable<E>> void sortTest(String path, String method, E[] arrs) throws Exception {
        Class<?> sortClass = Class.forName(path);
        Method sort = sortClass.getMethod(method,Comparable[].class);
        long start = System.nanoTime();
        System.out.println("start:" + start);
        sort.invoke(sortClass.newInstance(), (Object) arrs);
        long end = System.nanoTime();
        System.out.println("end:" + start);
        System.out.println("over:" + (end - start) / 1000000000.0 + "s");
        if (SortingHelp.isSorted(arrs)) {
            System.out.println("true");
        } else {
            System.out.println("false");
        }
    }
}
